package com.study.nio;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

/**
 * @author zhuzi
 * 2024/7/3 14:18
 */
@Slf4j
public class Demo {


    @Test
    public void d1() {
        String path = "/Users/zhuzi/Downloads/sql/新建.txt";

        try (FileChannel channel = new FileInputStream(path).getChannel()) {

            //准备缓存区
            ByteBuffer buffer = ByteBuffer.allocate(10);

            while (true) {
                //重channel读取数据
                int read = channel.read(buffer);
                if (read == -1) {
                    break;
                }
                //打印buffer|切换到读取模式
                buffer.flip();

                while (buffer.hasRemaining()) {
                    byte b = buffer.get();
                    System.out.println((char) b);
                }
                buffer.clear();
            }

        } catch (IOException e) {
        }
    }

    @Test
    public void d2byteBufferWrite() {
        //分配容量不能动态调整
        ByteBuffer buffer = ByteBuffer.allocate(10);
        buffer.put((byte) 0x61);
    }

    @Test
    public void dCopy() throws IOException {
        Path path = Paths.get("/Users/zhuzi/Pictures/壁纸/1066910.png");
        Path target = Paths.get("/Users/zhuzi/Pictures/壁纸/A-1066910.png");
        // 目标文件存在会报错FileAlreadyExistsException
        Files.copy(path, target, StandardCopyOption.REPLACE_EXISTING);
    }

    @Test
    public void dserver() throws IOException {
        ServerSocketChannel ssc = ServerSocketChannel.open();
    }

    
}

